package com.ag.lzw.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ag.bean.TbUserDept;
import com.ag.common.IDUtil;
import com.ag.lzw.dao.LzwTbUserDeptDAO;
import com.ag.lzw.service.impl.HandelTasksImpl;
import com.ag.lzw.service.impl.Lzw_IIDServiceImpl;
import com.ag.lzw.vo.NewTaskVo;

@Service("AutoAddTask")
public class AutoAddTask {

	@Resource(name = "handelTaskImpl")
	private HandelTasksImpl handelTasks;
	@Resource(name="lzw_IIDServiceImpl")
	Lzw_IIDServiceImpl idSerImpl;
	@Resource(name = "lzwTbUserDeptDAO")
	private LzwTbUserDeptDAO userDept;

	/**
	 * 
	 * @param uid 受任人ID
	 * @param did1 部门ID1
	 * @param did2  部门ID2 
	 * @param eventId 当前事件ID
	 * @param currentUserId 当前用户的ID
	 * @return boolean
	 */
	public boolean autoTask(String uid, String did1, String did2,
			String eventId, String currentUserId) {

		List<String> ids = idSerImpl.findTablePK(IDUtil.TB_TASK,3);
		
		List<NewTaskVo> tasks = new ArrayList<NewTaskVo>();

		if (ids != null && ids.size() == 1) {
			NewTaskVo newtask1 = new NewTaskVo();
			newtask1.setId(ids.get(0));
			newtask1.setEId(eventId);
			newtask1.setUserID(uid);
			newtask1.setTime(DateHandeler.DateToString(new Date()));
			newtask1.setB(currentUserId);
			newtask1.setName("");
			newtask1.setContext("");
			List<TbUserDept> list = userDept.findDeptByUid(uid);
			for(TbUserDept ud : list){
				newtask1.setDeptID(ud.getUdId());
			}
			
			NewTaskVo newtask2 = new NewTaskVo();
			newtask2.setId(ids.get(1));
			newtask2.setEId(eventId);
			newtask2.setTime(DateHandeler.DateToString(new Date()));
			newtask2.setB(currentUserId);
			newtask2.setName("");
			newtask2.setContext("");
			newtask2.setDeptID(did1);
			List<TbUserDept> list2 = userDept.findUserDeptByDid(did1);
			for(TbUserDept ud:list2){
				newtask2.setUserID(ud.getTbUser().getUId());
			}
			
			NewTaskVo newtask3 = new NewTaskVo();
			newtask3.setId(ids.get(2));
			newtask3.setEId(eventId);
			newtask3.setTime(DateHandeler.DateToString(new Date()));
			newtask3.setB(currentUserId);
			newtask3.setName("");
			newtask3.setContext("");
			newtask3.setDeptID(did1);
			List<TbUserDept> list3 = userDept.findUserDeptByDid(did2);
			for(TbUserDept ud:list3){
				newtask3.setUserID(ud.getTbUser().getUId());
			}
			
			tasks.add(newtask1);
			tasks.add(newtask2);
			tasks.add(newtask3);
			
			if(handelTasks.saveTasks(tasks)){
				return true;
			} else {
				return false;
			}
			
		} else {
			return false;
		}
	}
}
